<template>
  <search-table
    ref="searchTable"
    :columns="userListCol"
    :data="userIntegralData"
    :total="userIntegralTotal"
    :page.sync="currentPage"
    :size.sync="compitionPZ"
    @change-size="userIntegralChangeSize"
    @change-page="userIntegralOnChange"
  >
    <Collapse simple slot="alert">
      <Panel name="1">
        手动操作
        <p slot="content" class="button-group">
          <!--<Button type="primary" icon="md-add" @click="doIntegralCom">积分计算</Button>-->
          <Button type="primary" icon="ios-download-outline" @click="doOutputReport(1)"
            >导出计分排行(Excel)</Button
          >
          <Button type="primary" icon="ios-download-outline" @click="doOutputReport4PDF(1)"
            >导出计分排行(PDF)</Button
          >
        </p>
      </Panel>
    </Collapse>
  </search-table>
</template>

<script>
import {
  integralCom,
  cancelIntegralCom,
  outputExport,
  listCtfIntegral,
  listUserCtfIntegral,
  getCtfGameboxlist
} from '@/api/compitionStatic'
import { exportReport4PDF } from '@/api/competition'
import { getSenceUserList, queryAllKnowLedgeQuestion } from '@/api/knowledgeCompet'
import commonFun from '../mixin.js' //一些公共方法(获取比赛人员和比赛题目等)，用来判断是否可以计算积分，开始比赛等等
export default {
  name: 'klgUserIntegral',
  components: {},
  mixins: [commonFun],
  inject: ['detailParent'],
  data() {
    return {
      userIntegralData: [],
      userIntegralTotal: 0,
      scenceId: '',
      scenceName: '',
      list: [],
      formValidate: {
        matchMode: '3'
      },
      compitionPZ: 10,
      currentPage: 1,
      userListCol: [
        {
          title: '排名',
          key: 'rank',
          align: 'center',
          placement: 'top-left',
          order: 2
        },
        {
          title: '选手名称',
          key: 'teamName',
          placement: 'top-left',
          order: 1
        },

        {
          title: '有效总分',
          key: 'score'
        },
        {
          title: '积分（百分制）',
          key: 'integral'
        }
      ],
      userTotal: 0,
      quesTotal: 0,
      canCalc: false
    }
  },
  filters: {},
  computed: {
    competeDetail() {
      return this.detailParent.competeDetail
    }
  },
  mounted() {
    this.validateStart(false).then((data) => {
      if (data) {
        this.canCalc = true
      }
      this.getUserKlgIntegral()
    })
  },
  beforeDestroy() {
    clearTimeout(this.timeout)
  },
  methods: {
    userIntegralChangeSize(page) {
      this.compitionPZ = page
      this.getUserKlgIntegral()
    },
    userIntegralOnChange(page) {
      this.currentPage = page
      this.getUserKlgIntegral()
    },
    doOutputReport4PDF(contestType) {
      let str = '团队积分'
      if (contestType === 1) {
        str = '个人积分'
      }
      exportReport4PDF(this.competeDetail.id, this.competeDetail.name).then((data) => {
        console.log(data)
        let url = window.URL.createObjectURL(data) //表示一个指定的file对象或Blob对象
        let a = document.createElement('a')
        document.body.appendChild(a)
        let fileName = this.competeDetail.name + str + '.pdf' //filename名称截取
        a.href = url
        a.download = fileName //命名下载名称
        a.click() //点击触发下载
        window.URL.revokeObjectURL(url) //下载完成进行释放
      })
    },
    doOutputReport(contestType) {
      let _this = this
      let params = {
        contestId: _this.competeDetail.id,
        contestName: _this.competeDetail.name,
        contestType: contestType,
        matchMode: '3'
      }
      let str = '团队积分'
      if (contestType === 1) {
        str = '个人积分'
      }
      outputExport(params).then((data) => {
        console.log(data) //打印出来是blob对象，已经不是乱码了
        let url = window.URL.createObjectURL(data) //表示一个指定的file对象或Blob对象
        console.log(url, '看一下这是啥')
        let a = document.createElement('a')
        document.body.appendChild(a)
        let fileName = _this.competeDetail.name + str + '.xls' //filename名称截取
        a.href = url
        a.download = fileName //命名下载名称
        a.click() //点击触发下载
        window.URL.revokeObjectURL(url) //下载完成进行释放
      })
    },
    getUserKlgIntegral(page, pageSize) {
      let _this = this
      let params = {}
      params.page = _this.currentPage || 1
      params.rows = _this.compitionPZ || 10
      let id = ''
      if (_this.competeDetail.id) {
        //查看资源分配信息，如果长度为0 ，则分配
        let params1 = {
          page: 1,
          rows: 20000,
          contestId: _this.competeDetail.id
        }

        listUserCtfIntegral(_this.competeDetail.id, '3', params).then((data) => {
          if (data.code == 1) {
            _this.userIntegralData = data.attribute.dataList
            if (_this.userIntegralData.length <= 0) {
              //&& this.$route.query.activityStatus == '2'
              //如果没有积分信息，而且比赛结束,则重新计算
              if (this.canCalc) {
                _this.doIntegralCom()
              }
              //              _this.timeout = setTimeout(() => {
              //              	_this.getUserKlgIntegral();
              //              },3000)
            }
            _this.userIntegralTotal = data.attribute.totalCount
          }
        })
      }
    },
    doIntegralCom(num) {
      let _this = this
      cancelIntegralCom(_this.competeDetail.id).then((data) => {
        if (data.code == 1) {
          integralCom(_this.competeDetail.id, '3').then((data) => {
            if (data.code == 1) {
              if (!num) {
                _this.$Message.success('积分计算成功!')
                _this.getUserKlgIntegral()
              }
            } else {
              //_this.$Message.success(data.message);
            }
          })
        } else {
          //_this.$Message.success(data.message);
        }
      })
    }
    //    getSenceUserList(){
    //    	return new Promise((resolve,reject) => {
    //    		let params = {
    //	          page:1,
    //	          rows:10,
    //	          refId:this.competeDetail.id
    //	      	}
    //	      	getSenceUserList(params).then(data=>{
    //			      if(data.code==1){
    //			        this.userTotal = data.attribute.totalCount;
    //			        resolve(this.userTotal);
    //			      }else{
    //			      	resolve(0);
    //			      }
    //			    }).catch(error => {
    //			    	resolve(0);
    //			    })
    //    	})
    //    },
    //    queryAllQuestion(){
    //    	return new Promise((resolve,reject) => {
    //	        let queryObj = {
    //	          page:1,
    //	          rows:10
    //	        };
    //	        queryAllKnowLedgeQuestion(this.competeDetail.id,queryObj).then(data=>{
    //	          if(data.code===1){
    //	            this.quesTotal = data.attribute.totalCount;
    //	            resolve(this.quesTotal);
    //	          }else{
    //				      	resolve(0);
    //			      }
    //			    }).catch(error => {
    //			    	resolve(0);
    //			    })
    //		    })
    //    },
  }
}
</script>
<style>
.tables .ivu-poptip-body {
  text-align: left !important;
}
</style>
<style scoped>
#access {
  display: flex;
  flex-direction: column;
}
.Titles {
  background: #eeeeee;
  margin: 16px auto;
  padding: 10px 0;
}

.targetHeader {
  padding: 10px;
  margin-bottom: 10px;
}
.button-group /deep/ .ivu-btn {
  margin-right: 10px;
}
</style>
